<?php

namespace backend\controllers;

use backend\models\CommentsSearch;
use common\models\Comments;
use common\models\CommentsReply;
use common\models\GoodsDetail;
use services\models\UpFileData;
use Yii;
use backend\models\CommentsRelation;

use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use services\models\ProhibitedWords;

/**
 * CommentsRelationController implements the CRUD actions for CommentsRelation model.
 */
class CommentsRelationController extends MyController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionTest(){
        $model = new CommentsRelation();
        $model->updateFeedbackRate(1);
    }

    /**
     * Lists all CommentsRelation models.
     * @return mixed
     */
    public function actionIndex()
    {

        $searchModel = new CommentsRelation();
        $params = Yii::$app->request->queryParams;

        if(Yii::$app->request->isGet) {
            if(!empty($params['CommentsRelation']['goods_name']))//商品名称搜索
            {

                $goods_name = $params['CommentsRelation']['goods_name'];
                $searchModel->goods_name = $goods_name;
                $all_id = (GoodsDetail::find()->select('goods_id')->where(['like','goods_name',$goods_name])->asArray()->all());
                $goods_ids = '';
                foreach($all_id as $val){
                    $goods_ids .= $val['goods_id'].',';
                }
                $goods_ids = rtrim($goods_ids,',');
                if(!empty($goods_ids)) {
                    $params['goods_ids'] = $goods_ids;

                }else {
                    $params['goods_ids'] = 0;
                }

            }

        }

        $dataProvider = $searchModel->search($params);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single CommentsRelation model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $ImgArr = explode(',',$model['comments']->img);
        //var_dump(count($ImgArr));die;
        $forImg = UpFileData::showImages($model['comments']->img, count($ImgArr));
        //var_dump($forImg);die;
        $model['comments']->img = implode($forImg,' ');

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new CommentsRelation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CommentsRelation();
        $commentsModel = new CommentsSearch();

        if ( $model->load(Yii::$app->request->post()) && $commentsModel->load(Yii::$app->request->post()) && $commentsModel->save()) {
            //var_dump($commentsModel->comment_id);
            $model->comment_id = $commentsModel->comment_id;
            if($model->save()){
                $update = new CommentsSearch();
                $update->updateRedis($model->comment_id);
            }

            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
                'm'=> $commentsModel,
            ]);
        }
    }

    /*
     * 检测敏感字
     * */
    public function actionProhibited(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $content = Yii::$app->request->post('content');
        $prohibit = new ProhibitedWords();
        $test = $prohibit->filterForComments($content);//判断是否有敏感词
        if(!$test['flag']){
            return ['flag' => false, 'msg' => '您输入的“'.$test['msg'].'”可能涉及敏感词汇，请重新输入'];
        }
        return ['flag' => true];
    }

    /**
     * Updates an existing CommentsRelation model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $m = CommentsSearch::findOne($model->comment_id);

/*
        $imgNo = count(explode(',',$m->img));//计算图片个数
        $pathArr = array();
        if($imgNo > 0) {
            $pathArr = UpFileData::showImages($m->img, $imgNo);
        }*/

        if ($model->load(Yii::$app->request->post()) && $m->load(Yii::$app->request->post()) && $model->save() && $m->save()) {

            $comment = new CommentsRelation();
            $comment->updateCommentRedis($model->comment_id);
            $comment->updateUserCommentNumberToRedis($model->bestry_uid);//更新用户评论条数
            $comment->updateCommentDetailRedis(\yii\helpers\ArrayHelper::toArray($m));//更新评论详情

            if($model->reply_id > 0)
                $comment->updateReplyRedis($model->reply_id, \yii\helpers\ArrayHelper::toArray($model));

            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
                'm'=> $m,
            ]);
        }
    }

    /**
     * Deletes an existing CommentsRelation model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $relationModel = $this->findModel($id);
        //var_dump($relationModel->comment_id);
        $model = new Comments();
        $comments = $model->findOne($relationModel->comment_id);
        if(!empty($comments)) {
            $comments->delete();//删除comments表里的相关记录
            //var_dump($commentsModel);die;
        }

        $replyModel = new CommentsReply();
        $reply = $replyModel->findOne($relationModel->reply_id);
        if(!empty($reply)){
            $reply->delete();//删除comments_reply表里的相关记录
        }
        $this->findModel($id)->delete();//删除comments_relation表里的相关记录

        return $this->redirect(['index']);
    }

    /**
     * Finds the CommentsRelation model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CommentsRelation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CommentsRelation::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionChangeShow(){//是否展示，0，不展示，1、展示

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');

        if(intval($id) < 1) {
            return ['status'=>1,'msg'=>'缺少参数'];
        }
        $result = CommentsRelation::findOne($id);

        if(empty($result)) {
            return ['status'=>2,'msg'=>'未查询到信息'];
        }

        $is_show = $result->is_show == 0 ? 1 : 0;

        $result->is_show = $is_show;

        $result->save();

        $relation = new CommentsRelation();
        $relation->updateCommentRedis($result->comment_id);//评论详情
        //$relation->updateGoodAndBad($result->comment_id);//好中差评

        return ['status'=>0,'msg'=>'修改成功'];
    }

    public function actionChangeStatus(){//评论状态，-1：待审核，0：普通，1：精华，2：不通过

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');
        $status = Yii::$app->request->post('status');
        if(intval($id) < 1) {
            return ['status'=>1,'msg'=>'缺少参数'];
        }
        $result = CommentsRelation::findOne($id);

        if(empty($result)) {
            return ['status'=>2,'msg'=>'未查询到信息'];
        }
        $old_status = $result->status;//原状态
        $result->status = intval($status);
        $result->save();

        /*刷新用户试豆mysql+redis*/
        CommentsRelation::addScore($old_status, $status, $result->bestry_uid);

        $relation = new CommentsRelation();
        $relation->updateCommentRedis($result->comment_id);//刷新评论redis
        $relation->updateUserCommentNumberToRedis($result->bestry_uid);//刷新用户评论数redis
        return ['status'=>0,'msg'=>'修改成功'];
    }

    public function actionReply(){

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');
        $content = Yii::$app->request->post('content');
        if(intval($id) < 1) {
            return ['status'=>1,'msg'=>'缺少参数'];
        }
        $result = CommentsRelation::findOne($id);

        if(empty($result)) {
            return ['status'=>2,'msg'=>'未查询到信息'];
        }


        $replyModel = new CommentsReply();

        $reply =$replyModel->findOne(['comment_id'=>$result->comment_id]);

        if(empty($reply)) {//保存回复信息
            $replyModel->comment_id = $result->comment_id;
            $replyModel->content = $content;
            $replyModel->admin_id = 0;
            $replyModel->create_time =  date("Y-m-d H:i:s");
            $replyModel->update_time = date("Y-m-d H:i:s");
            $replyModel->save(true);//保存 comments_reply
            $result->reply_id = $replyModel->reply_id;
        } else{//更新回复信息
            $reply->content = $content;
            $reply->update_time = date("Y-m-d H:i:s");
            $reply->save();//更新 comments_reply
            $result->reply_id = $reply->reply_id;
        }

        $result->is_reply = 1;
        $result->save();//更新 comments_relation

        $relation = new CommentsRelation();
        $relation->updateReplyRedis($result->reply_id, \yii\helpers\ArrayHelper::toArray($result));
        $relation->updateUserCommentNumberToRedis($result->bestry_uid);

        return ['status'=>0,'msg'=>'回复成功'];

    }

    //批量审核
    public function actionBatch($ids, $op){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $idList = explode(',', $ids);//待批量处理的id列表

        foreach($idList as $id) {
            $relationModel = CommentsRelation::findOne($id);
            if(!empty($relationModel)) {
                $old_status = $relationModel->status;
                if (1 == $op) {//批量审核不通过
                    $status = 2;
                    $relationModel->status = $status;

                } elseif (2 == $op) {//批量精华评论
                    $status = 1;
                    $relationModel->status = $status;
                }

                if($old_status != $status){
                    $relationModel->save();

                    //试豆操作
                    CommentsRelation::addScore($old_status,$status,$relationModel->bestry_uid);
                }

                $relation = new CommentsRelation();
                $relation->updateCommentRedis($relationModel->comment_id);
                $relation->updateUserCommentNumberToRedis($relationModel->bestry_uid);

            }
        }
        return ['status'=>0, 'msg'=>'批量处理完毕'];
    }

    //批量回复
    public function actionPReply(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $idList = explode(',', Yii::$app->request->post('ids'));
        $pContent = Yii::$app->request->post('content');
        //var_dump($pContent);
        if(empty($idList)) {
            return ['status'=>1,'msg'=>'缺少参数'];
        }

        foreach($idList as $id){
            $result = CommentsRelation::findOne($id);
            if(empty($result)) {
                return ['status'=>2,'msg'=>'未查询到信息'];
            }

            $replyModel = new CommentsReply();
            $reply =$replyModel->findOne(['comment_id'=>$result->comment_id]);

            if(empty($reply)) {//保存回复信息
                $replyModel->comment_id = $result->comment_id;
                $replyModel->content = $pContent;
                $replyModel->admin_id = 0;
                $replyModel->create_time = date("Y-m-d H:i:s");
                $replyModel->update_time = date("Y-m-d H:i:s");
                $replyModel->save(true);//保存 comments_reply
                $result->reply_id = $replyModel->reply_id;
            } else{//更新回复信息
                $reply->content = $pContent;
                $reply->update_time = date("Y-m-d H:i:s");
                $reply->save();//更新 comments_reply
                $result->reply_id = $reply->reply_id;
            }

            $result->is_reply = 1;
            $result->save();//更新 comments_relation

            $relation = new CommentsRelation();
            $relation->updateReplyRedis($result->reply_id, \yii\helpers\ArrayHelper::toArray($result));
            $relation->updateUserCommentNumberToRedis($result->bestry_uid);
        }
        return ['status'=>0,'msg'=>'批量回复成功'];
    }

}
